package com.example.shushiyunsst.fragment.main.mine.child

import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSON
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.KeyboardUtils
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.constant.CURRENT_DEVICE_TOKEN
import com.example.shushiyunsst.fragment.main.mine.child.bean.ServiceCustomerBean
import com.example.shushiyunsst.util.SERVICE_CUSTOMER
import com.example.wallet.db.UserInfoManager
import com.example.wallet.utils.Preference
import ikidou.reflect.TypeBuilder
import java.lang.reflect.Type

@Route(path = SERVICE_CUSTOMER)
class ServiceCustomerFragment : SimpleListFragment<ServiceCustomerBean>(),
    KeyboardUtils.OnSoftInputChangedListener {

    override fun getItemLayout(): Int {
        return R.layout.service_customer_fragment
    }

    private lateinit var msgEdt: EditText

    private lateinit var sendBtn: ImageView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        KeyboardUtils.registerSoftInputChangedListener(_mActivity, this)
//        pageIndex = 0
        isAddDividerItemDecoration = false
        isEnableLoadMore = false
    }

    override fun initView(view: View) {
        super.initView(view)
        mHeader.removeAllViews()
        addHeader(R.layout.comment_header_layout)
        mHeader.setBackgroundResource(R.color.bg_color_0)
        view.setBackgroundResource(R.color.bg_color)
        val mToolbar: Toolbar = mHeader.findViewById(R.id.mToolbar)
        mToolbar.title = "客服"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        mFooter.removeAllViews()
        addFooter(R.layout.service_customer_footer_fragment)
        msgEdt = mFooter.findViewById(R.id.msgEdt)
        sendBtn = mFooter.findViewById(R.id.sendBtn)

        msgEdt.setOnClickListener {
            showSoftInput(view)
        }
        sendBtn.setOnClickListener {
            val msg = msgEdt.text.toString()
            sendMsg(msg)
            hideSoftInput()
        }
    }

    private fun sendMsg(msg: String) {
        if (msg.isEmpty()) return
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val map = mapOf(
            "contentDesc" to msg,
            "uid" to userInfo?.uid
        )

        RestClient.builder()
            .url(R.string.saveCouService)
            .raw(JSON.toJSONString(map))
            .success {
                if (!mSwipeRefreshLayout.isRefreshing){
                    mSwipeRefreshLayout.isRefreshing=true
                }
                onRefresh()
            }.failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_LONG).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_LONG).show()
            }.build().post()
    }

    override fun convertItem(helper: JssBaseViewHolder?, item: ServiceCustomerBean?) {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        helper?.setText(R.id.receiverTv,item?.contentDesc)
            ?.setText(R.id.timeTv,item?.createTime)
            ?.setText(R.id.sendTv,item?.contentDesc)
            ?.setViewVisible(R.id.receiverLayout,item?.boardType==2)
            ?.setViewVisible(R.id.sendLayout,item?.boardType==1)
            ?.setImageResource(R.id.receiverAvatar,R.mipmap.app_icon_1)
            ?.setImageNetUrl(R.id.sendAvatar,userInfo?.userLogo,R.mipmap.image_load_err)
    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(ServiceCustomerBean::class.java).endSubType().build()
    }

    override fun netRequest() {
//        val raw = Utils.getJsonFromRaw(_mActivity, R.raw.temp_fack_data)
//        parseDate(raw)

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val deviceTokens = Preference.HOLDER.getCustomAppProfile(CURRENT_DEVICE_TOKEN)
        val map = mapOf(
            "deviceToken" to deviceTokens,
            "uid" to userInfo?.uid
        )

        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.queryMyCouServiceList)
            .success { parseDate(it) }
            .failure { onFailed() }
            .error { _, _ -> onFailed() }
            .build().post()
    }

    override fun parseDate(data: String?) {
//        super.parseDate(data)
        val obj = JSON.parseObject(data)
        val list = obj["list"] ?: ""
        val array = JSON.parseArray(JSON.toJSONString(list), ServiceCustomerBean::class.java)
        loadListDate(array)
        mRecyclerView.scrollToPosition(mAdapter.data.size - 1)
        delayedTime=0
    }

    override fun onSoftInputChanged(height: Int) {
        val lp = mFooter.layoutParams as LinearLayout.LayoutParams
        lp.bottomMargin = height
        mFooter.layoutParams = lp
        if (height > 0) {
            msgEdt.requestFocus()
            mRecyclerView.scrollToPosition(mAdapter.data.size - 1)
        } else {
            msgEdt.clearFocus()
            msgEdt.setText("")
        }


    }

    override fun onDestroy() {
        super.onDestroy()
        KeyboardUtils.unregisterSoftInputChangedListener(_mActivity)
    }
}